package com.yiwei.zhh.api.requestInfo;

import com.yiwei.zhh.api.Api;
import com.yiwei.zhh.api.bean.InitAppBean;
import com.yiwei.zhh.api.callback.InitAppContract;
import com.yiwei.zhh.constant.Const;
import com.yiwei.zhh.model.InitAppModel;
import com.yiwei.zhh.util.ExceptionEngine;
import com.yiwei.zhh.util.Network;
import com.yiwei.zhh.util.PackageUtil;
import com.yiwei.zhh.util.PreferenceUtils;
import com.yiwei.zhh.util.RBInfo;
import com.yiwei.zhh.util.RxLifeUtil;
import com.yiwei.zhh.util.ToastUtil;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;

/**
 * Created by Administrator on 2017/5/14.
 */

public class InitAppRequest extends BaseRequest<InitAppContract.View> implements InitAppContract.Presenter<InitAppContract.View> {

    public static InitAppRequest create() {
        return new InitAppRequest();
    }


    @Override
    public void initApp() {
        if (!Network.checkNetwork(BaseContext)) {
            ToastUtil.makeText(BaseContext, networkFail).show();
            return;
        }
        mView.onRequestStart();
        InitAppBean bean = new InitAppBean();
        bean.client_type = Const.CLIENT_TYPE;
        bean.device_id = RBInfo.getInstance().getUniquePsuedoID();
        bean.user_agent = RBInfo.getInstance().getUserAgent();
        bean.os = Const.DevType.ANDROID;
        bean.os_version = RBInfo.getInstance().getOSVersion();

        bean.browser = "";
        bean.browser_version = "";
        bean.mobile_brand = RBInfo.getInstance().getBrand();
        bean.mobile_model = RBInfo.getInstance().getModel();
        bean.app_version = PackageUtil.getVersionName(BaseContext);
        double lat = PreferenceUtils.getDouble(BaseContext.getApplicationContext(), Const.KEY.LAT, -1);
        double lng = PreferenceUtils.getDouble(BaseContext.getApplicationContext(), Const.KEY.LNG, -1);
        if (lat > 0 && lng > 0) {
            bean.lat = lat;
            bean.lang = lng;
        }


        Api.api_service.getInitInfo(bean).compose(RxLifeUtil.NoErrorOn(BaseContext))

                .doOnError(throwable -> {

                    mView.showError();
                })
                .onErrorResumeNext(new Function<Throwable, ObservableSource<? extends InitAppModel>>() {
                    @Override
                    public ObservableSource<? extends InitAppModel> apply(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                        return Observable.empty();
                    }
                }).
                subscribe(result -> {
                    mView.initAppSuccess(result);
                });
    }
}
